﻿using System.Collections.Generic;
using smp.QueryDb.Structure;

namespace smp.QueryDb.Executing
{
    public class Insert
    {
        private Command _command;
        private readonly List<InsertValue> _parameters = new List<InsertValue>();


        public Insert(Table table)
        {
            if (table == null)
                throw Helper.Error("Cannot initialise Insert with null table");
            if (table.IsReadOnly)
                throw Helper.Error("Cannot insert data in a read only table or view");

            _command = new Command();
            _command.CommandBuilder.AppendFormat("INSERT INTO {0} (", table.Declaration);
        }

        public IInsertValue Set(Column column)
        {
            _command.CommandBuilder.AppendFormat(" [{0}],", column.Name);
            return new InsertValue(this, column);
        }

        internal void AddSetParameter(InsertValue insertValue)
        {
            _parameters.Add(insertValue);
        }

        internal ICommand GetCommand(IDbAdapter adapter)
        {
            _command.CommandBuilder.Remove(_command.CommandBuilder.Length - 1, 1);
            _command.CommandBuilder.Append(") VALUES (");

            foreach(var set in _parameters)
            {
                var parameterName = string.Format("{0}P_{1}", adapter.ParameterPix, _command.Parameters.Count);
                _command.CommandBuilder.AppendFormat(" {0},", parameterName);
                _command.AddParameter(set.CreateParameter(parameterName));
            }
            _command.CommandBuilder.Remove(_command.CommandBuilder.Length - 1, 1);
            _command.CommandBuilder.Append(")");
            return _command;
        }
    }
}
